//
//  HomeViewControler.m
//  SlowLoad
//
//  Created by Hai Nguyen on 8/28/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HomeViewControler.h"
#import "News.h"
#import "NewsCell.h"

#define kCUSTOM_ROW_HEIGHT    80
#define kCUSTOM_ROW_COUNT     6

@implementation HomeViewControler
@synthesize newsTable;
@synthesize homeCell;
@synthesize loadingView;
@synthesize newsArray;
@synthesize imageDownloadsInProgress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma -
#pragma NewsParserDelegate Method
-(void) didEndGetNews:(NSMutableArray*) arrayStoreNews{
	[imageDownloadsInProgress removeAllObjects];
	[self.loadingView setHidden:YES];
	[self.newsArray setArray:arrayStoreNews];
	NSLog(@"News : %@", arrayStoreNews);
	[self.newsTable reloadData];
}

#pragma -
#pragma TableView Delegate Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [self.newsArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *homeCellId = @"CellID";
	homeCell = (NewsCell*)[tableView dequeueReusableCellWithIdentifier:homeCellId];
	if (homeCell == nil) {
		[[NSBundle mainBundle] loadNibNamed:@"NewsCell" owner:self options:nil];
	}
	News *news = [self.newsArray objectAtIndex:[indexPath row]];
	[homeCell.titleLabel setText:news.title];
	[homeCell.descriptionLabel setText:news.description];
	if (!news.thumbnailImage){
		if (self.newsTable.dragging == NO && self.newsTable.decelerating == NO){
			[self startIconDownload:news forIndexPath:indexPath];
		}              
	}
	else{
		self.homeCell.thumbnailImage.image = news.thumbnailImage;
		[self.homeCell.activity removeFromSuperview];
	}
	
	return homeCell;
}

#pragma mark -
#pragma mark Table cell image support
- (void)startIconDownload:(News*)news forIndexPath:(NSIndexPath *)indexPath{
    ImageDownloader *imageDownloader = [imageDownloadsInProgress objectForKey:indexPath];
    if (imageDownloader == nil) {
        imageDownloader = [[ImageDownloader alloc] init];
        imageDownloader.news = news;
        imageDownloader.indexPathInTableView = indexPath;
        imageDownloader.delegate = self;
        [imageDownloadsInProgress setObject:imageDownloader forKey:indexPath];
        [imageDownloader startDownload];
        [imageDownloader release];   
    }
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([self.newsArray count] > 0){
        NSArray *visiblePaths = [newsTable indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths){
            News *news = [self.newsArray objectAtIndex:indexPath.row];
            
            if (!news.thumbnailImage) {
				// avoid the app icon download if the app already has an icon
                [self startIconDownload:news forIndexPath:indexPath];
            }
        }
    }
}

// called by our ImageDownloader when an icon is ready to be displayed
- (void)appImageDidLoad:(NSIndexPath *)indexPath
{
    ImageDownloader *imageDownload = [imageDownloadsInProgress objectForKey:indexPath];
    if (imageDownload != nil){
        self.homeCell = (NewsCell*)[newsTable cellForRowAtIndexPath:imageDownload.indexPathInTableView];        
		self.homeCell.thumbnailImage.image = imageDownload.news.thumbnailImage;
		[self.homeCell.activity removeFromSuperview];
    }
}

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!decelerate){
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self loadImagesForOnscreenRows];
}

- (void)didReceiveMemoryWarning{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
	[self.view addSubview:loadingView];
	[self.loadingView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
	[self.loadingView setHidden:NO];
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
	self.newsArray = [[[NSMutableArray alloc] init] autorelease];
	NewsParser *newsParser = [[NewsParser alloc] init];
	[newsParser getNewsFromUrl:@"http://vnexpress.net/rss/gl/trang-chu.rss" withDelegate:self];
	[newsParser release];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) dealloc{
	self.homeCell = nil;
	self.newsTable = nil;
	self.loadingView = nil;
	self.newsArray = nil;
	self.imageDownloadsInProgress = nil;
	[super dealloc];
}

@end
